package com.hengtongxing.hejiayun.shop;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;


import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.bean.ShopCartListBean;
import com.hengtongxing.hejiayun.bean.ShopListBean;
import com.hengtongxing.hejiayun.event.AddressEvent;
import com.hengtongxing.hejiayun.event.CartRefushEvent;
import com.hengtongxing.hejiayun.shop.adapter.ShopCartListAdapter;
import com.hengtongxing.hejiayun.shop.model.IShopModel;
import com.hengtongxing.hejiayun.shop.model.ShopModelImpl;
import com.hengtongxing.hejiayun.utils.FastClickUtils;
import com.hengtongxing.hejiayun.utils.NumberFormatUtils;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.CommonNoTitleDialog;
import com.hengtongxing.hejiayun.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopCartActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_all_choose)
    ImageView ivAllChoose;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_all_choose)
    TextView tvAllChoose;
    @BindView(R.id.ll_commit)
    LinearLayout llCommit;
    @BindView(R.id.tv_clear_cart)
    TextView tvClearCart;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;
    private IShopModel shopModel;
    private boolean isEdit;
    private ShopCartListAdapter listAdapter;
    private List<ShopCartListBean.DataBean.ItemListBean> beanList;
    private boolean isAllChoose;
    private CommonNoTitleDialog.Builder dialogBuild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_cart);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
    }

    @Subscribe
    public void cartRefushEvent(CartRefushEvent event) {
        requestShopCartShow();
    }

    public void initView() {
        shopModel = new ShopModelImpl();
        titleBar.setRightClickListener(() -> {
            if (!isEdit) {
                titleBar.setTitleRightText("完成");
                llCommit.setVisibility(View.GONE);
                llDelete.setVisibility(View.VISIBLE);
            } else {
                titleBar.setTitleRightText("编辑");
                llCommit.setVisibility(View.VISIBLE);
                llDelete.setVisibility(View.GONE);
            }
            isEdit = !isEdit;
        });

        beanList = new ArrayList<>();
        listAdapter = new ShopCartListAdapter(beanList);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener((type, position) -> {
            if (FastClickUtils.isFastClick()) {
                return;
            }
            ShopCartListBean.DataBean.ItemListBean dataBean = beanList.get(position);
            //减少
            if (type == 1) {
                if (dataBean.getNum() > 1) {
                    dataBean.setNum(dataBean.getNum() - 1);
                    requestShopCartEdit(String.valueOf(dataBean.getId()), String.valueOf(dataBean.getNum()));
                }
            }
            //增加
            if (type == 2) {
                dataBean.setNum(dataBean.getNum() + 1);
                requestShopCartEdit(String.valueOf(dataBean.getId()), String.valueOf(dataBean.getNum()));
            }
            //选择
            if (type == 3) {
                dataBean.setCheck(!dataBean.isCheck());
            }
            listAdapter.notifyDataSetChanged();
            setTotalPrice();
        });
        requestShopCartShow();
    }

    /**
     * 购物车 列表
     */
    public void requestShopCartShow() {
        shopModel.requestIntegralShopCartShow(new DataCallBack<ShopCartListBean>() {
            @Override
            public void onSuccessful(ShopCartListBean bean) {
                beanList.clear();
                if (bean.getData() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                }
                listAdapter.notifyDataSetChanged();
                setTotalPrice();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 编辑数量
     */
    public void requestShopCartEdit(String id, String num) {
        shopModel.requestIntegralShopCartEdit(id, num, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestShopCartDelete(String id) {
        shopModel.requestIntegralShopCartDelete(id, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("删除成功");
                Iterator<ShopCartListBean.DataBean.ItemListBean> it_b = beanList.iterator();
                while (it_b.hasNext()) {
                    ShopCartListBean.DataBean.ItemListBean a = it_b.next();
                    if (id.equals(a.getId() + "")) {
                        it_b.remove();
                    }
                }
                listAdapter.notifyDataSetChanged();
                setTotalPrice();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void setTotalPrice() {
        String totalMoney = "0";
        int itemNum = 0;
        for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
            if (dataBean.isCheck()) {
                itemNum++;
                totalMoney = NumberFormatUtils.formatDouble(Double.parseDouble(totalMoney) + dataBean.getNum() * Double.parseDouble(dataBean.getPrice()) / 100);
            }
        }
        tvTotalPrice.setText(totalMoney);

        if (itemNum > 0) {
            tvCommit.setText("去结算(" + itemNum + ")");
        } else {
            tvCommit.setText("去结算");
        }
        if (beanList.size() != 0 && itemNum == beanList.size()) {
            ivAllChoose.setImageResource(R.mipmap.ic_order_xuanze);
            isAllChoose = true;
        } else {
            ivAllChoose.setImageResource(R.mipmap.ic_order_kongyuan);
            isAllChoose = false;
        }
    }

    @OnClick({R.id.iv_all_choose, R.id.tv_all_choose, R.id.tv_commit, R.id.tv_clear_cart, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_all_choose:
            case R.id.tv_all_choose:
                if (!isAllChoose) {
                    for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                        dataBean.setCheck(true);
                    }
                    ivAllChoose.setImageResource(R.mipmap.ic_order_xuanze);
                } else {
                    for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                        dataBean.setCheck(false);
                    }
                    ivAllChoose.setImageResource(R.mipmap.ic_order_kongyuan);
                }
                isAllChoose = !isAllChoose;
                listAdapter.notifyDataSetChanged();
                setTotalPrice();
                break;
            case R.id.tv_commit:
                List<ShopCartListBean.DataBean.ItemListBean> mList = new ArrayList<>();
                for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                    if (dataBean.isCheck()) {
                        mList.add(dataBean);
                    }
                }
                if (mList.size() == 0) {
                    ToastUtil.showShort("请先选择商品");
                    return;
                }
                Intent intent = new Intent(mActivity, ShopConfirmOrderActivity.class);
                intent.putExtra("itemList", (Serializable) mList);
                startActivity(intent);
                break;
            case R.id.tv_clear_cart:
                List<String> list = new ArrayList<>();
                for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                    list.add(dataBean.getGoods_id() + "");
                }
                if (list.size() == 0) {
                    return;
                }
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("确定清空购物车？");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                        requestShopCartDelete(dataBean.getId() + "");
                    }
                });
                dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();

                break;
            case R.id.tv_delete:
                list = new ArrayList<>();
                for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                    if (dataBean.isCheck()) {
                        list.add(dataBean.getGoods_id() + "");
                    }
                }
                if (list.size() == 0) {
                    ToastUtil.showShort("请先选择删除的商品");
                    return;
                }
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("确定删除商品？");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    for (ShopCartListBean.DataBean.ItemListBean dataBean : beanList) {
                        if (dataBean.isCheck()) {
                            requestShopCartDelete(dataBean.getId() + "");
                        }
                    }
                });
                dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
        }
    }
}
